package com.huang.usercenter.service.impl;

import com.huang.usercenter.Exception.BusinessException;
import com.huang.usercenter.common.ErrorCode;
import com.huang.usercenter.model.domain.User;
import com.huang.usercenter.service.UserService;
import com.huang.usercenter.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.huang.usercenter.constant.UserConstant.FALT;
import static com.huang.usercenter.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author 14748
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2023-02-03 14:23:46
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public long userRegister(String userAccount, String password, String checkPassword, String planetCode) {
        //校验
        if (!checkMessage(userAccount, password)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "用户账户或用户密码不合法");
        }
        if (StringUtils.isAnyBlank(checkPassword, planetCode)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR);
        }
        if (planetCode.length() > 5) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "星球编号太长了");
        }
        //密码和校验码相同
        if (!password.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "两次密码不一致");
        }
        //账户不能重复
        User findResult = userMapper.getOneByUserAccount(userAccount);
        if (findResult != null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "用户账户不能重复");
        }
        //星球编号不能重复
        findResult = userMapper.getOneByPlanetCode(planetCode);
        if (findResult != null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "星球编号不能重复");
        }
        //将密码进行加密
        String encryptPassword = DigestUtils.md5DigestAsHex((FALT + password).getBytes());

        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
        boolean saveResult = userMapper.saveUser(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "保存失败");
        }
        return user.getId();
    }


    @Override
    public User userLogin(String userAccount, String password, HttpServletRequest request) {
        // 校验
        if (!checkMessage(userAccount, password)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "用户账户或用户密码不合法");
        }
        //将密码进行加密
        String encryptPassword = DigestUtils.md5DigestAsHex((FALT + password).getBytes());

        //查询用户是否存在
        User findResult = userMapper.getOneByUserAccountAndPassword(userAccount, encryptPassword);
        //如果不存在
        if (findResult == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "用户账户不存在");
        }
        //如果存在
        User safetyUser = getSafetyUser(findResult);

        //保存到session中
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);
        return safetyUser;
    }

    @Override
    public List<User> SearchUsers(String username) {
//        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
//        if (StringUtils.isNotBlank(username)) {
//            wrapper.like(User::getUsername, username);
//        }
        List<User> userList = userMapper.listWithUsername(username).stream().map(this::getSafetyUser).collect(Collectors.toList());
        return userList;
    }

    @Override
    public User getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User user = (User) userObj;
        Long userId = user.getId();
        //判断该用户是否合法
        return userMapper.getById(userId);
    }

    @Override
    public int logout(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }

    @Override
    public boolean removeById(long id) {
        return userMapper.removeById(id);
    }

    @Override
    public Boolean updateById(User user) {
        return userMapper.updateById(user);
    }

    public Boolean saveUser(User user) {
        return userMapper.saveUser(user);
    }

    // 用户信息脱敏
    public User getSafetyUser(User user) {
        if (user == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User safetyuser = new User();
        safetyuser.setId(user.getId());
        safetyuser.setUsername(user.getUsername());
        safetyuser.setUserAccount(user.getUserAccount());
        safetyuser.setAvatarUrl(user.getAvatarUrl());
        safetyuser.setGender(user.getGender());
        safetyuser.setPhone(user.getPhone());
        safetyuser.setEmail(user.getEmail());
        safetyuser.setUserStatus(user.getUserStatus());
        safetyuser.setPlanetCode(user.getPlanetCode());
        safetyuser.setCreateTime(user.getCreateTime());
        safetyuser.setUserRole(user.getUserRole());

        return safetyuser;

    }

    //用户校验
    private boolean checkMessage(String userAccount, String password) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, password)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "用户账户或用户密码为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "用户账户太短了");
        }
        if (password.length() < 8) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "用户密码太短了");
        }
        //账户不包含特殊字符
        String validPattern = "[^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (!matcher.find()) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "用户账户不能包含特殊字符");
        }
        return true;
    }
}




